<template>
  <div class="wrapper">
    <v-head></v-head>
    <v-sidebar></v-sidebar>
    <div class="content-box" :class="{'content-collapse':collapse}">
      <v-tags></v-tags>
      <div :class="content_class" >
        <transition name="move" mode="out-in">
          <!-- <keep-alive :include="tagsList"> -->
            <router-view></router-view>
          <!-- </keep-alive> -->
        </transition>
      </div>
    </div>
    <!-- 修改密码 -->
    <el-dialog title="密码修改" :visible.sync="isShow" v-dialogDrag :before-close="handleClose">
      <div slot="title" class="header-title">
          <div class="header-title-div"></div>
          <div class="header-title-text">密码修改</div>
      </div>
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item label="原密码" :label-width="formLabelWidth" prop="beforepwd">
            <el-input v-model="form.beforepwd" autocomplete="off" show-password placeholder="请输入原密码" clearable></el-input>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth" prop="currentpwd">
          <el-tooltip class="item" effect="dark" content="密码格式：大小写字母或数字" placement="top-start">
            <el-input v-model="form.currentpwd" autocomplete="off" placeholder="请输入新密码" show-password clearable></el-input>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="confirmpwd">
            <el-input show-password v-model="form.confirmpwd" placeholder="请输入确认密码" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 确定弹出框 -->
    <el-dialog title="请重新登陆" :visible.sync="isLogin"  :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <div slot="title" class="header-title">
          <div class="header-title-div"></div>
          <div class="header-title-text">请重新登陆</div>
      </div>
      <h1>密码修改成功！请重新登陆！</h1>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exitMethod">退出系统</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import mixin from '@/mixin/mixin.js';
import $ from 'jquery'
import vHead from "./Header.vue";
import vSidebar from "./Sidebar.vue";
import vTags from "./Tags.vue";
import bus from "./bus";
import { mapGetters } from "vuex";
import { mapActions } from "vuex";
export default {
  mixins: [mixin],
  data() {
    const self = this;
    return {
      rules:{
        beforepwd: [
            { required: true, message: '请输入原密码', trigger: 'blur' },
            // {
            //     validator: (rule, value, callback) => {
            //     if (!(/^[0-9a-zA-Z]+$/).test(value.trim())) {
            //         callback(new Error('密码格式错误！'));
            //     } else {
            //         // 校验密码是否正确
            //         let params = {
            //             id:localStorage.getItem("userId"),
            //             password:value.trim()
            //         };
            //         self.$axios({
            //             method: 'get',
            //             url: `/index//validatePassword`,
            //             headers:{
            //                 Authorization: this.requestToken   
            //             },
            //             data: params,
            //             params: params
            //         }).then(res=>{
            //             console.log(res.data)
            //             if(res.data.code == '20000'){
            //                 callback()
            //             }else{
            //                 callback(new Error('原密码输入错误！'));
            //             }
            //         }).catch(err=>{
            //             callback(new Error(err));
            //         })
            //     }
            //     },
            //     trigger: 'blur'
            // }
        ],
        currentpwd: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
            {
                validator: (rule, value, callback) => {
                  if(value && value.length){
                    if (!(/^[0-9a-zA-Z]+$/).test(value.trim())) {
                        callback(new Error('密码格式错误！'));
                    } else {
                        callback()
                    }
                  }else{
                    callback()
                  }
                  
                },
                trigger: 'blur'
            }
        ],
        confirmpwd: [
            { required: true, message: '请输入确认密码', trigger: 'blur' },
            {
                validator: (rule, value, callback) => {
                if (!(/^[0-9a-zA-Z]+$/).test(value.trim())) {
                    callback(new Error('密码格式错误！'));
                } else {
                  if(value.trim() == self.form.currentpwd){
                    callback();
                  }else{
                    self.form.confirmpwd = '';  
                    callback(new Error('确认密码与新密码不一致！'));
                  }
                }
                },
                trigger: 'blur'
            }
        ]
      },
      isLogin:false,
      tagsList: [],
      collapse: false,
      form: {
        beforepwd: '',
        currentpwd: '',
        confirmpwd: ''
      },
      content_class:'content',
      formLabelWidth: '120px'
    };
  },
  computed: {
    ...mapGetters("dailog", {
      isShow: "isShow"
    })
  },
  methods: {
    ...mapActions("dailog", ["hideDailog", "showDailog"]),
    // 修改密码取消
    handleClose(){
      this.form = {
        beforepwd: '',
        currentpwd: '',
        confirmpwd: ''
      }
      this.$refs['form'].resetFields();
      this.hideDailog();
    },
    // 点击退出
    exitMethod(){
      let self = this;
      self.showLoading();
      let userinfo = JSON.parse(localStorage.getItem("userinfo"))
      $.ajax({
          type:"get",                            
          url:`/wgry/index/logout?username=${userinfo.accountName}`,
          timeout:30000,
          async: false,
          cache: false,
          success: function (res) {
            self.hideLoading();
              if(res.code == '20000'){
                  self.$router.push("/login");
                  localStorage.removeItem("ms_username");
                  localStorage.removeItem("token");
                  localStorage.removeItem("userinfo");
                  self.$message.success(res.message)
              }else{
                  self.$message.error(res.message)
              }
          },
          error:function(err){
            self.hideLoading();
            self.$message.error(err)
          }
      })
    },
    // 修改密码提交
    submit(){
      let self = this;
      this.$refs['form'].validate((valid) => {
          if (valid) {
            self.showLoading();
              let params = {
                  id:localStorage.getItem("userId"),
                  password:self.form.beforepwd,
                  passwordSure:self.form.confirmpwd
              };
              self.$axios({
                  method: 'post',
                  url: `/index/modifyPassword`,
                  headers:{
                      Authorization: this.requestToken   
                  },
                  data: params,
                  params: params
              }).then(res=>{
                  self.hideLoading();
                  if(res.data.code == '20000'){
                      self.hideDailog();
                      self.$refs['form'].resetFields();
                      self.form = {
                        beforepwd: '',
                        currentpwd: '',
                        confirmpwd: ''
                      }
                      localStorage.removeItem("token");
                      self.isLogin = true;
                  }else{
                      self.$message.error(res.data.message)
                  }
              }).catch(err=>{
                  self.hideLoading();
                  self.$message.error(err)
              })
          } else {
              return false;
          }
      });
    },
  },
  components: {
    vHead,
    vSidebar,
    vTags
  },
  created() {
    bus.$on("collapse", msg => {
      this.collapse = msg;
    });
    bus.$on("content", msg => {
      this.content_class = msg;
    });
    // 只有在标签页列表里的页面才使用keep-alive，即关闭标签之后就不保存到内存中了。
    bus.$on("tags", msg => {
      let arr = [];
      for (let i = 0, len = msg.length; i < len; i++) {
        msg[i].name && arr.push(msg[i].name);
      }
      this.tagsList = arr;
    });
  }
};
</script>
